/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.category;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantOperCode;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.DBInitId;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.Dictionary;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.service.category.CategoryService;
import org.grayrabbit.cms.service.category.impl.CategoryCache;
import org.grayrabbit.cms.service.content.ContentService;
import org.grayrabbit.cms.service.system.AdminOperRelaService;
import org.grayrabbit.cms.service.system.AdminService;
import org.grayrabbit.cms.service.system.RoleOperRelaService;
import org.grayrabbit.cms.util.FilePathSptUtil;
import org.grayrabbit.cms.vo.category.CategoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.grayrabbit.dao.util.Page;

/**
 * <b>CategoryAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 14:38:49 
 */
@Controller
@Scope("prototype")
@Results( {
		@Result(name = "reload", type = "redirect", location = "category-list"),
		@Result(name = "input", type = "dispatcher", location = "category-input.jsp"),
		@Result(name = "success", type = "dispatcher", location = "category-list.jsp")	
		}
		)
public class CategoryAction extends BaseAction<CategoryBean> {
	private static final long serialVersionUID = -1L;
	private static final String AUDIT_CATEGORY = "category"; 
	private static final String AUDIT_TOPIC = "topic"; 		
	//Service接口接入
	@Autowired
	@Qualifier("categoryServiceImpl")
	private CategoryService categoryService;
 
 
	@Autowired
	@Qualifier("adminServiceImpl")
	private AdminService adminService;
	@Autowired
	@Qualifier("contentServiceImpl")
	private ContentService contentService;
	
	@Autowired
	@Qualifier("roleOperRelaServiceImpl")
	private RoleOperRelaService roleOperRelaService;
	@Autowired
	@Qualifier("adminOperRelaServiceImpl")
	private AdminOperRelaService adminOperRelaService;
	
	
	private List<Dictionary> dicIsComment;
	private List<Dictionary> dicIsInitcomment;
	private List<Dictionary> dicIsAudit;
	private List<Dictionary> dicIsContribute;
	private List<Dictionary> dicIsLink;
	public List<Dictionary> getDicIsLink() {
		return dicIsLink;
	}

	public void setDicIsLink(List<Dictionary> dicIsLink) {
		this.dicIsLink = dicIsLink;
	}

	private List<Site> siteList = new ArrayList<Site>();
	private String adminName;
	private String catname;
	private String flag;
	private String simName;
	private String oldsimName;
	private String targetId;
	private String auditType;
	private boolean refresh;
	
	public String getAdminName() {
		return adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}

	public List<Dictionary> getDicIsComment() {
		return dicIsComment;
	}

	public void setDicIsComment(List<Dictionary> dicIsComment) {
		this.dicIsComment = dicIsComment;
	}

	public List<Dictionary> getDicIsInitcomment() {
		return dicIsInitcomment;
	}

	public void setDicIsInitcomment(List<Dictionary> dicIsInitcomment) {
		this.dicIsInitcomment = dicIsInitcomment;
	}

	public List<Dictionary> getDicIsAudit() {
		return dicIsAudit;
	}

	public void setDicIsAudit(List<Dictionary> dicIsAudit) {
		this.dicIsAudit = dicIsAudit;
	}

	public List<Dictionary> getDicIsContribute() {
		return dicIsContribute;
	}

	public void setDicIsContribute(List<Dictionary> dicIsContribute) {
		this.dicIsContribute = dicIsContribute;
	}
	
	public String getSimName() {
		return simName;
	}

	public void setSimName(String simName) {
		this.simName = simName;
	}

	public String getOldsimName() {
		return oldsimName;
	}

	public void setOldsimName(String oldsimName) {
		this.oldsimName = oldsimName;
	}

	//VO对象，由前端页面数据组装
	private CategoryBean category;
	
	private String parentId;
	
	private String upId;
	
	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}
	public List<Site> getSiteList() {
		return siteList;
	}

	public void setSiteList(List<Site> siteList) {
		this.siteList = siteList;
	}

	public String getUpId() {
		return upId;
	}

	public void setUpId(String upId) {
		this.upId = upId;
	}

	/**return 前端页面数据组装VO对象,<b>CategoryBean</b>*/
	public CategoryBean getCategory() {
		return category;
	}

	public void setCategory(CategoryBean category) {
		this.category = category;
	}
	
	//分页对象
	private Page<Category> page = new Page<Category>(MAX_PAGE_NUM,true);
	
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	public Page<Category> getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	public void setPage(Page<Category> page) {
		this.page = page;
	}
	
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(category==null){
			category = new CategoryBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public CategoryBean getModel() {
		return category;
	}
	
	//批量操作时使用的传入的ID
	private String ids;
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	
	@Override
	protected void prepareModel(){
		Category cate = null;
		if(category != null && category.getCategory()!=null && StringUtils.isNotBlank(category.getCategory().getCategoryId())){
			cate = categoryService.getCategory(category.getCategory().getCategoryId());
		}
		if(category != null && StringUtils.isNotBlank(category.getCategoryId())){
			category = (CategoryBean)dozer.map(categoryService.getCategory(category.getCategoryId()),CategoryBean.class);
		}
		if(cate!=null){
			category.setCategory(cate);
		}
	}

	
	/**
	 * 删除<b>Category</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到category-list.action
	 */
	@Override
	@Action(value="category-delete",
			results={@Result(name="reload",type="redirectAction",params={"actionName","category-list?category.categoryId=${category.category.categoryId}&flag=delok"})}
			)
	public String delete(){
		categoryService.delete(key);
		roleOperRelaService.deleteObjectAuth(key,ConstantOperCode.AUTH_CAT_TYPE);
		adminOperRelaService.deleteObjectAuth(key,ConstantOperCode.AUTH_CAT_TYPE);
		Category obj = null;
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		List<Category> list = categoryService.catList(category.getCategory().getCategoryId(),currentSite.getSiteId());
		for(int i=0;i<list.size();i++){
			obj = categoryService.getCategory(list.get(i).getCategoryId());
			obj.setOrd(i+1);
			categoryService.save(obj);
		}
		for(int i=0;i<key.length;i++){
			addLog(Module.CAT.getValue(),OperAct.DEL.getValue(),key[i]);
		}
		saveMemoryHandle(currentSite.getSiteId());
		return RELOAD;
	}
	
	
	/**
	 * Category的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到category-list.jsp页面
	 */
 
	@Override
	@Action(value="category-list")
	public String list(){
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		category.setSite(currentSite);
		categoryService.listNumCount(page,category);
		if(!DBInitId.CMS_SUPPER_ADMIN_ID.equals(getCurrentAdminId())){			
			@SuppressWarnings("unchecked")
			Set<String> authSet = (Set<String>)getSessionValue(ConstantWebApp.CURRENT_ADMIN_AUTH_CODE);
			List<Category> list= page.getResult();
			List<Category> result= new ArrayList<Category>();	
			for(Category c : list){
				if(result.contains(c)) continue; 
				for(String s : authSet){ 
					 if(s.equals(ConstantOperCode.CAT_CAT_EDIT+"-"+c.getCategoryId()) 
					   ||s.equals(ConstantOperCode.CAT_CAT_GEN+"-"+c.getCategoryId() )){						 				 
						 result.add(c); 
						 break;
					 }
				}
				 
			} 
			page.setResult(result);
		}
		//是否刷新栏目树
		refresh = CategoryCache.getSiteCategoriesFlag(getCurrentSiteId());		
		return SUCCESS;
	}
	
	/**
	 * Category的新增与编辑的方法执行成功能
	 * 将映射到category-input.jsp
	 */
	@Action(value="category-input")
	public String input(){
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_COMMENT)!=null){
			dicIsComment = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_COMMENT);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_INITCOMMENT)!=null){
			dicIsInitcomment = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_INITCOMMENT);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_AUDIT)!=null){
			dicIsAudit = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_AUDIT);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_CONTRIBUTE)!=null){
			dicIsContribute = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_CONTRIBUTE);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_LINK)!=null){
			dicIsLink = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_LINK);
		}
		prepareModel();
		if(category != null && StringUtils.isNotBlank(category.getCategoryId())){
			List<Admin> list = adminService.AllAuditorAdmins(
					ConstantOperCode.AUTH_CAT_TYPE, category.getCategoryId());
			if(list != null && !list.isEmpty()){
				StringBuffer sb = new StringBuffer();
				int index = list.size() ;
				for(Admin a : list){
					sb.append(a.getLoginName());
					index -- ;
					if(index >0) sb.append(",");				
				}
				category.setAuditor(sb.toString());
			}
		}
		return INPUT;
	}
	
	/**
	 * save or update Category的方法，将成员property category转成Category实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到category-list.action
	 */
	@Override
	@Action(value="category-save",
			results={@Result(name="reload",type="redirectAction",params={"actionName","category-list?category.categoryId=${category.category.categoryId}"})}
		)
	public String save(){
		Category obj = null;
		Category item = null;
		if(StringUtils.isNotBlank(category.getCategoryId())){
			item = categoryService.getCategory(category.getCategoryId());
			obj = (Category) dozer.map(category, Category.class);
			obj.setSite(item.getSite());
		}else{
			obj = (Category) dozer.map(category, Category.class);
		}
		if(category.getCategory()!=null && StringUtils.isNotBlank(category.getCategory().getCategoryId())){
			obj.setCategory(category.getCategory());
		}
		if(!StringUtils.isNotBlank(obj.getCategoryId())){
			obj.setCategoryId(null);
		}
		Admin admin = getCurrentAdmin();
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(!StringUtils.isNotBlank(obj.getCategoryId())){
			if(admin != null){
				obj.setCreateLoginName(admin.getLoginName());
				obj.setCreateRealName(admin.getRealName());
			}
			obj.setCreateTime(new Date());
			Boolean t=true;
			obj.setCategoryStatus(t);
			obj.setSite(currentSite);
			List<Category> list = categoryService.catList(category.getCategory().getCategoryId(),currentSite.getSiteId());
			if(list.size()>0){
				obj.setOrd(list.get(list.size()-1).getOrd()+1);
			}else{
				obj.setOrd(1);
			}
		}else{
			obj.setUpdateTime(new Date());
			if(admin != null){
				obj.setUpdateLoginName(admin.getLoginName());
				obj.setUpdateRealName(admin.getRealName());
			}
		}
		String catname = category.getCatName().trim();
		obj.setCatName(catname);
		String catsimpname = category.getCatSimpleName().trim();
		obj.setCatSimpleName(catsimpname);
		obj.setAuditor(null);
		categoryService.save(obj);
		String auditors = category.getAuditor();
		distributeAuditAuthCode(obj.getCategoryId(),ConstantOperCode.AUTH_CAT_TYPE,ConstantOperCode.CAT_DOC_AUDIT,auditors);
		saveMemoryHandle(currentSite.getSiteId());
		//创建栏目时给其赋予相应的权限
		 
	 
		if(StringUtils.isBlank(category.getCategoryId())){
			addObjectDistributeAuthCode(obj.getCategoryId(),ConstantOperCode.AUTH_CAT_TYPE,ConstantOperCode.CAT_CAT_EDIT);
			addLog(Module.CAT.getValue(),OperAct.ADD.getValue(),obj.getCategoryId());
		}else{
			addLog(Module.CAT.getValue(),OperAct.EDIT.getValue(), category.getCategoryId());
		}
		return RELOAD;
	}
	/**
	 * 栏目名称唯一验证
	 * @return
	 */
	@Action(value="category-checknameunique")
	public String  checkNameUnique(){
		String text="";
		try{
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			Boolean unique=categoryService.checkNameUnique(category.getCatName().trim(),category.getCategory().getCategoryId(),currentSite.getSiteId(),catname);
			if(!unique){
				text="ok";
			}else{
				text="no";
			}
		}catch(Exception e){
			text="no";
		}
		return renderText(text);
	}
	/**
	 * 栏目简称唯一验证
	 * @return
	 */
	@Action(value="category-checksimpleunique")
	public String  checksimpleunique(){
		String text="";
		try{
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			Boolean unique=categoryService.checksimpleunique(category.getCatSimpleName().trim(),currentSite.getSiteId(),oldsimName);
			if(!unique){
				text="ok";
			}else{
				text="no";
			}
		}catch(Exception e){
			text="no";
		}
		return renderText(text);
	}
 
	
	private String treeType;

	public String getTreeType() {
		return treeType;
	}

	public void setTreeType(String treeType) {
		this.treeType = treeType;
	}
	
	/**
	 * 新增、删除、 编辑 栏目时调用，变更内存栏目树更新标志
	 * @param CurrentSiteId  当前站点ID
	 */
	private void saveMemoryHandle(String CurrentSiteId){
		if(StringUtils.isBlank(CurrentSiteId))
			return ;
		CategoryCache.removeSiteCategoriesAndFlagInfo(CurrentSiteId);
		CategoryCache.removeAuthCatsAndFlagbySiteIds(CurrentSiteId);		
	}
 
	
	/**
	 * 禁用/启用站点
	 * @return
	 */
	@Action(value="category-disableorenable")
	public String disableOrEnable(){
		
		String text="";
		Category obj=null;
		try {
			if(null!=category&&StringUtils.isNotBlank(category.getCategoryId())){
				obj= categoryService.getCategory(category.getCategoryId());
				if(null!=obj.getCategoryStatus()&&!obj.getCategoryStatus()){
					obj.setCategoryStatus(true);
					addLog(Module.CAT.getValue(),OperAct.ENABLE.getValue(), category.getCategoryId());
				}else{
					obj.setCategoryStatus(false);
					addLog(Module.CAT.getValue(),OperAct.DISABLE.getValue(), category.getCategoryId());
				}
				categoryService.save(obj);
			}
			text="ok";
		} catch (Exception e) {
			log.debug(e.getMessage());
			text="no";
		}
		return renderText(text);
	}
	
	/**
	 * 批量操作，ID处理
	 * @return
	 */
	private String[] getBatchIds(){
		String[] idBatchs=null;
		if((null!=ids)&&(StringUtils.isNotBlank(ids))){
			if(ids.contains("on")){
				idBatchs=ids.substring(3).split("@");
			}else{
				idBatchs=ids.split("@");
			}
			
		}
		return idBatchs;
	}
	/**
	 * 批量禁用
	 */
	@Action(value="category-batchdisable")
	public String batchDisable(){
		String text="";
		try {
			String[] idBatchs=getBatchIds();
			for(int j=0;j<idBatchs.length;j++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[j])){
					text = "sorry";
					continue;
				}else{
					categoryService.disable(idBatchs);
					for(int i=0;i<idBatchs.length;i++){
						addLog(Module.CAT.getValue(),OperAct.DISABLE.getValue(),idBatchs[i]);
					}
					text="ok";
				}
			}
			
		} catch (Exception e) {
			text="no";
			log.debug(e.getMessage());
		}
		return renderText(text);
	}
	/**
	 * 批量启用
	 */
	@Action(value="category-batchenable")
	public String batchEnable(){
		String text="";
		try {
			String[] idBatchs=getBatchIds();
			for(int j=0;j<idBatchs.length;j++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[j])){
					text = "sorry";
					continue;
				}else{
					categoryService.enable(idBatchs);
					for(int i=0;i<idBatchs.length;i++){
						addLog(Module.CAT.getValue(),OperAct.ENABLE.getValue(),idBatchs[i]);
					}
					text="ok";
				}
			}
			
		} catch (Exception e) {
			text="no";
			log.debug(text);
		}
		return renderText(text);
	}
	
	/**
	 * 上移
	 * @return
	 */
	@Action(value="category-upmove")
	public String upMove(){
		Category obj=null;
		Category upObj = null;
		if(null!=category&&StringUtils.isNotBlank(category.getCategoryId())){
			obj= categoryService.getCategory(category.getCategoryId());
			upObj = categoryService.getCategory(upId);
			Integer cord= obj.getOrd();
			Integer uord = upObj.getOrd();
			obj.setOrd(uord);
			upObj.setOrd(cord);
			categoryService.save(obj);
			categoryService.save(upObj);
			addLog(Module.CAT.getValue(),OperAct.UP.getValue(),upId);
			addLog(Module.CAT.getValue(),OperAct.DOWN.getValue(), category.getCategoryId() );
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
		}
		return null;
	}
	/**
	 * 下移
	 * @return
	 */
	@Action(value="category-downmove")
	public String downMove(){
		
		Category obj=null;
		Category upObj = null;
		if(null!=category&&StringUtils.isNotBlank(category.getCategoryId())){
			obj= categoryService.getCategory(category.getCategoryId());
			upObj = categoryService.getCategory(upId);
			Integer cord= obj.getOrd();
			Integer uord = upObj.getOrd();
			obj.setOrd(uord);
			upObj.setOrd(cord);
			categoryService.save(obj);
			categoryService.save(upObj);
			addLog(Module.CAT.getValue(),OperAct.UP.getValue(), category.getCategoryId());
			addLog(Module.CAT.getValue(),OperAct.DOWN.getValue(), upId);
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
		}
		return null;
	}
	/**
	 * 栏目移动
	 * @return
	 */
	@Action(value="category-catmove")
	public String catMove(){
		Category obj=null;
		String oldparentId=null;
		if(null!=category&&StringUtils.isNotBlank(category.getCategoryId())){
			obj= categoryService.getCategory(category.getCategoryId());
			if(obj.getCategory()!=null){
				oldparentId=obj.getCategory().getCategoryId();
			}
			if(parentId.equals("top")){
				parentId=null;
				obj.setCategory(null);
			}else{
				obj.setCategory(new Category(parentId));
			}
			categoryService.save(obj);
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			List<Category> list = categoryService.catList(parentId,currentSite.getSiteId());
			if(list.size()>0){
				Category itemlist=null;
				for(int i=0;i<list.size();i++){
					itemlist=list.get(i);
					itemlist.setOrd(i+1);
					categoryService.save(itemlist);
				}
			}
			List<Category> oldlist=categoryService.catList(oldparentId,currentSite.getSiteId());
			if(oldlist.size()>0){
				Category olditemlist=null;
				for(int i=0;i<oldlist.size();i++){
					olditemlist=oldlist.get(i);
					olditemlist.setOrd(i+1);
					categoryService.save(olditemlist);
				}
			}
			addLog(Module.CAT.getValue(),OperAct.MOVE.getValue(), category.getCategoryId());
			//Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
		}
		return null;
	}
	/**
	 * 栏目合并
	 * @return
	 */
	@Action(value="category-catmarge")
	public String catMarge(){
		String text="";
		Category obj=null;
		String oldCategoryId=null;
		if(null!=category&&StringUtils.isNotBlank(category.getCategoryId())){
			//查询父Id为...category.getCategoryId() 的栏目
			obj= categoryService.getCategory(category.getCategoryId());
			if(obj.getCategory()!=null){
				oldCategoryId=obj.getCategory().getCategoryId();
			}
			List<Category> list = categoryService.findByParentId(category.getCategoryId(),category);
			for(int i=0;i<list.size();i++){
				obj= categoryService.getCategory(list.get(i).getCategoryId());
				obj.setCategory(new Category(parentId));
				categoryService.save(obj);
				addLog(Module.CAT.getValue(),OperAct.MERGE.getValue(), category.getCategoryId());
			}
			List<Category> listnew = categoryService.findByParentId(parentId,category);
			for(int i=0;i<listnew.size();i++){
				obj= categoryService.getCategory(listnew.get(i).getCategoryId());
				obj.setOrd(i+1);
				categoryService.save(obj);
				addLog(Module.CAT.getValue(),OperAct.MERGE.getValue(), category.getCategoryId());
			}
			Category item=categoryService.getCategory(category.getCategoryId());
			List <Content> listcontent=contentService.findByCatId(category.getCategoryId());
			if(listcontent.size()!=0){
				for(int i=0;i<listcontent.size();i++){
					listcontent.get(i).setCategory(new Category(parentId));
					contentService.save(listcontent.get(i),getCurrentAdmin(),null);
				}
			
			}
			categoryService.delete(item);
			addLog(Module.CAT.getValue(),OperAct.DEL.getValue(), category.getCategoryId());
			List<Category> listold = categoryService.findByParentId(oldCategoryId,category);
			for(int i=0;i<listold.size();i++){
				obj= categoryService.getCategory(listold.get(i).getCategoryId());
				obj.setOrd(i+1);
				categoryService.save(obj);
				addLog(Module.CAT.getValue(),OperAct.MERGE.getValue(), category.getCategoryId());
			}
			
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
			text="yes";
			return renderText(text);
		}
		return null;
	}
	
	/**
	 * 栏目批量合并
	 * @return
	 */
	@Action(value="category-batchcatmerge")
	public String BatchCatMerge(){
		String text = "";
		Category obj=null;
		String oldparentId=null;
		Category oldobj=null;
		String[] idBatchs=getBatchIds();
		if(idBatchs.length>0){
			//查询父Id为...category.getCategoryId() 的栏目
			oldobj= categoryService.getCategory(idBatchs[0]);
			if(oldobj.getCategory()!=null){
				oldparentId=oldobj.getCategory().getCategoryId();
			} 
			for(int k=0;k<idBatchs.length;k++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[k])){
					text = "no";
					continue;
				}
				
				List <Content> listcontent=contentService.findByCatId(idBatchs[k]);
				if(listcontent.size()!=0){
					for(int i=0;i<listcontent.size();i++){
						listcontent.get(i).setCategory(new Category(parentId));
						contentService.save(listcontent.get(i),getCurrentAdmin(),null);
					}
				}
				
				List<Category> list = categoryService.findByParentId(idBatchs[k],category);
				for(int i=0;i<list.size();i++){
					obj= categoryService.getCategory(list.get(i).getCategoryId());
					obj.setCategory(new Category(parentId));
					categoryService.save(obj);
					addLog(Module.CAT.getValue(),OperAct.MOVE.getValue(), list.get(i).getCategoryId());
				}
			}
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			List<Category> list = categoryService.catList(parentId,currentSite.getSiteId());
			if(list.size()>0){
				Category itemlist=null;
				for(int i=0;i<list.size();i++){
					itemlist=list.get(i);
					itemlist.setOrd(i+1);
					categoryService.save(itemlist);
				}
			}
			for(int k=0;k<idBatchs.length;k++){
				Category item=categoryService.getCategory(idBatchs[k]);
				categoryService.delete(item);
				addLog(Module.CAT.getValue(),OperAct.DEL.getValue(), category.getCategoryId());
			}
		
			List<Category> oldlist=categoryService.catList(oldparentId,currentSite.getSiteId());
			if(oldlist.size()>0){
				Category olditemlist=null;
				for(int i=0;i<oldlist.size();i++){
					olditemlist=oldlist.get(i);
					olditemlist.setOrd(i+1);
					categoryService.save(olditemlist);
				}
			} 
			saveMemoryHandle(currentSite.getSiteId());
		}
		return renderText(text);
	}
	/**
	 * 栏目批量移动
	 * @return
	 */
	@Action(value="category-batchcatmove")
	public String BatchCatMove(){
		String text = "";
		Category obj=null;
		Category oldobj=null;
		String oldparentId=null;
		String[] idBatchs=getBatchIds();
		if(parentId.equals("top")){
			parentId=null;
		}
		if(idBatchs.length>0){	
			oldobj= categoryService.getCategory(idBatchs[0]);
			if(oldobj.getCategory()!=null){
				oldparentId=oldobj.getCategory().getCategoryId();
			} 
			for(int k=0;k<idBatchs.length;k++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[k])){
					text = "no";
					continue;
				}
				obj= categoryService.getCategory(idBatchs[k]);
				addLog(Module.CAT.getValue(),OperAct.MERGE.getValue(), idBatchs[k]);
				if(obj.getCategory() == null){//如果是顶级栏目
					obj.setCategory(new Category(parentId));
				}else{// 否则改变其父ID
					if(parentId==null){
						obj.setCategory(null);
					}else{
						obj.setCategory(new Category(parentId));
					}
					
				}
				categoryService.save(obj);
			}
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			List<Category> list = categoryService.catList(parentId,currentSite.getSiteId());
			if(list.size()>0){
				Category itemlist=null;
				for(int i=0;i<list.size();i++){
					itemlist=list.get(i);
					itemlist.setOrd(i+1);
					categoryService.save(itemlist);
				}
			}
			List<Category> oldlist=categoryService.catList(oldparentId,currentSite.getSiteId());
			if(oldlist.size()>0){
				Category olditemlist=null;
				for(int i=0;i<oldlist.size();i++){
					olditemlist=oldlist.get(i);
					olditemlist.setOrd(i+1);
					categoryService.save(olditemlist);
				}
			} 
			//Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
		}
		return renderText(text);
	}
	/**
	 * 查询 栏目（categoryID,categoryName）
	 * @return
	 */
	@Action(value="category-listall")
	public String findAll(){
		List<Category> list = categoryService.findALL(category);
		Map<String,Object> map =new HashMap<String,Object>(); 
		 JSONObject json = new  JSONObject();
		 JSONArray jsonArray = new JSONArray();
		for(int i=0;i<list.size();i++){
			map.put("categoryId", list.get(i).getCategoryId());
			map.put("catName", list.get(i).getCatName());
			map.put("categoryStatus", list.get(i).getCategoryStatus());
			json = JSONObject.fromObject( map ); 
			jsonArray.add(json);
		}
		return renderText(jsonArray.toString());
	}
	//批量删除
	@Action(value="category-batchcatdel")
	public String BatchCatDel(){
		String text = "";
		String oldparentid=null;
		String[] idBatchs=getBatchIds();
		if(idBatchs.length>0){
			Category oldobj=null;
			oldobj= categoryService.getCategory(idBatchs[0]);
			if(oldobj.getCategory()!=null){
			   oldparentid=oldobj.getCategory().getCategoryId();
			}
			for(int i=0;i<idBatchs.length;i++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[i])){
					text = "sorry";
					continue;
				}
				List<Category> list = categoryService.findByParentId(idBatchs[i], null);
				if(list.size()>0){
					text = "yes";
					break;
				}
			}
			if(!text.equals("yes")){
				categoryService.delete(idBatchs);
				Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
				List<Category> list = categoryService.catList(oldparentid,currentSite.getSiteId());
				if(list.size()>0){
					Category itemlist=null;
					for(int i=0;i<list.size();i++){
						itemlist=list.get(i);
						itemlist.setOrd(i+1);
						categoryService.save(itemlist);
					}
				}
				roleOperRelaService.deleteObjectAuth(idBatchs,ConstantOperCode.AUTH_CAT_TYPE);
				adminOperRelaService.deleteObjectAuth(idBatchs,ConstantOperCode.AUTH_CAT_TYPE);
			}
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			saveMemoryHandle(currentSite.getSiteId());
		}
		return renderText(text);
	}
	/**
	 * 删除时检查是否有子栏目
	 * @return
	 */
	@Action(value="category-checkischild")
	public String checkIsChild(){
		String text = "";
		List<Category> list = categoryService.findByParentId(category.getCategoryId(), category);
		if(list.size()>0){
			text = "yes";
		}else{
			text = "no";
		}
		return renderText(text);
	}
	
	/**
	 * 查询审核人
	 * @return
	 */
	@Action(value="category-authorsetselect")
	public String adminList(){
//		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
//		List<Admin> list = adminService.getAdminsByOper(currentSite.getSiteId(), ConstantOperCode.AUTH_SITE_TYPE, ConstantOperCode.SITE_TOPIC_AUDIT);
		List<Admin> list = adminService.getAllUsableAdmins();
		Map<String,Object> map =new HashMap<String,Object>(); 
		 JSONObject json = new  JSONObject();
		 JSONArray jsonArray = new JSONArray();
		for(int i=0;i<list.size();i++){
			map.put("adminId", list.get(i).getAdminId());
			map.put("loginName", list.get(i).getLoginName());
			map.put("realName",list.get(i).getRealName());
			json = JSONObject.fromObject( map ); 
			jsonArray.add(json);
		}
		return renderText(jsonArray.toString());
	}
	/**
	 * 设置审核人-save
	 * @return
	 */
	@Action(value="category-authorset")
	public String authorSet(){
		String text="";
		String[] idBatchs=getBatchIds();
		if(idBatchs != null){
			for(int i=0;i<idBatchs.length;i++){
				if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[i])){
					text="sorroy";return renderText(text);
				}
				Category categoryObj = categoryService.getCategory(idBatchs[i]);
				categoryObj.setAuditor(adminName);
				categoryService.save(categoryObj);
				distributeAuditAuthCode(categoryObj.getCategoryId(),ConstantOperCode.AUTH_CAT_TYPE,ConstantOperCode.CAT_DOC_AUDIT,adminName);
			}
		}else{
			Category categoryObj = categoryService.getCategory(category.getCategoryId());
			categoryObj.setAuditor(adminName);
			categoryService.save(categoryObj);
			addLog(Module.CAT.getValue(),OperAct.ADUIT.getValue(), category.getCategoryId());
			distributeAuditAuthCode(categoryObj.getCategoryId(),ConstantOperCode.AUTH_CAT_TYPE,ConstantOperCode.CAT_DOC_AUDIT,adminName);
		}
		text = "ok";
		addLog(Module.CAT.getValue(),OperAct.ADUIT.getValue(),category.getCategoryId());
		return renderText(text);
	}
	/**
	 * 根据id查找其子栏目
	 * @return
	 */
	@Action(value="category-findchildid")
	public String findChildId(){
		String childId = "";
			childId=categoryService.findByCategoryChildIds(category.getCategoryId());
		return renderText(childId);
	}

	/**
	 * 根据id查找其子栏目  副栏目
	 * @return
	 */
	@Action(value="category-findchildids")
	public String findChildIds(){
		String childId = "";
		try {			
			String[] idBatchs=getBatchIds();
			for(int i=0;i<idBatchs.length;i++){
				childId += categoryService.findByCategoryChildIds(idBatchs[i]);
				/**父 ID*/
				Category c = categoryService.findCatById(idBatchs[i]);
				if(c != null && c.getCategory() != null && 
						StringUtils.isNotBlank( c.getCategory().getCategoryId()))
					childId +=  c.getCategory().getCategoryId(); 
			}		 
		} catch (Exception e) {
			childId = "";
			log.error("栏目移动子栏目、父栏目查询异常", e);
		}
		return renderText(childId);
	}
	/**
	 * 根据栏目id查询文章列表
	 * @return
	 */
	@Action(value="category-checkhavecont")
	public String findContByCatId(){
		String text = "";
		String[] idBatchs=getBatchIds();
		if(idBatchs == null){
			List<Content> list = contentService.findByCatId(category.getCategoryId());
			if(list.size()>0){
				text = "yes";
			}else{
				text = "no";
			}
		}else{
			for(int i=0;i<idBatchs.length;i++){
				List<Content> list = contentService.findByCatId(idBatchs[i]);
				if(list.size()>0){
					text = "yes";
					break;
				}else{
					if(!authLicence(ConstantOperCode.CAT_CAT_EDIT, idBatchs[i])){
						text = "sorry";
						continue;
					}
				}
			}
			if(!text.equals("yes") && !text.equals("sorry")){
				categoryService.delete(idBatchs);
			}else{
				text = "no";
			}
		}
		return renderText(text);
	}
	
	/**
	 * 删除栏目下标题为空的文章
	 * @return
	 */
	@Action(value="category-delnullcontent")
	public String delNullContent(){
		String[] idBatchs=getBatchIds();
		if(idBatchs != null){
			for(int j=0;j<idBatchs.length;j++){
				List<Content> list = contentService.findByCatId(idBatchs[j]);
				for(int i=0;i<list.size();i++){
					String [] nullContent = new String[1];
					if(StringUtils.isBlank(list.get(i).getContentTitle())){
						nullContent[0]=list.get(i).getContentId();
						contentService.delete(nullContent);
					}
				}
			}
		}else{
			List<Content> list = contentService.findByCatId(category.getCategoryId());
			for(int i=0;i<list.size();i++){
				String [] nullContent = new String[1];
				if(StringUtils.isBlank(list.get(i).getContentTitle())){
					nullContent[0]=list.get(i).getContentId();
					contentService.delete(nullContent);
				}
			}
		}
		return null;
	}
	
	private String getParentName(Category obj){
		StringBuffer text = new StringBuffer();
		Category cat = categoryService.getCategory(obj.getCategoryId());
		if(cat.getCategory()!=null){
			text.append(getParentName(cat.getCategory()));
		}
		text.append(cat.getCatSimpleName()+"@");
		return text.toString();
	}
	
	/**
	 * 根据栏目id获取栏目简称
	 * @return
	 */
	@Action(value="category-getsimplename")
	public String getSimpleName(){
		Category obj = null;
		obj = categoryService.getCategory(category.getCategoryId());
		String text = getParentName(obj);
		String url = (obj.getSite().getSiteDomain()+FilePathSptUtil.URL_SPT+
				DictionaryStaticValues.CATEGORY+FilePathSptUtil.URL_SPT+
				text.replace("@", FilePathSptUtil.URL_SPT)+"index.html");
		File file = new File(FilePathSptUtil.LOCAL_SITE_PUBLISH_PATH+
				obj.getSite().getSiteShortName()+FilePathSptUtil.padLeftSpt(
				DictionaryStaticValues.CATEGORY)+FilePathSptUtil.padLeftSpt(
						text.replace("@", File.separator))+"index.html");
		if(file.exists()){
			return renderText("{flag:true,url:'"+url+"'}");
		}else{
			return renderText("{flag:false}");
		}
	}
	/**
	 * 验证是否是顶级栏目
	 * @return
	 */
	@Action(value="category-checkTopCategory")
	public String checkTopCategory(){
		String text="";
		String[] idBatchs=getBatchIds();
		Category obj=null;
		obj= categoryService.getCategory(idBatchs[0]);
		if(obj.getCategory()==null){
			text="no";
		}else{
			text="ok";
		}
		return renderText(text);
				
	}
	
	@Action(value="category-auditors")
	public String loadAuditors(){
	 
		if(StringUtils.isBlank(auditType) || StringUtils.isBlank(targetId) ){
			return renderText("{flag:false,msg:'参数异常，加载失败',auditor:'',hasAuth:false}");
		}
		List<Admin> list = null; 
		String text = null;
		try {			
			if(AUDIT_CATEGORY.equals(auditType)){
				list = adminService.AllAuditorAdmins(
						ConstantOperCode.AUTH_CAT_TYPE, targetId);
			}else if(AUDIT_TOPIC.equals(auditType)){
				list = adminService.AllAuditorAdmins(
						ConstantOperCode.AUTH_TOPIC_TYPE, targetId);
			}else{
				return renderText("{flag:false,msg:'参数异常，加载失败',auditor:'',hasAuth:false}");
			}
			String auditor = "";
			if(list != null && !list.isEmpty()){ 
				auditor = list.get(0).getLoginName();
			}		
			boolean hasAuth = hasAuth(null, list);
			StringBuffer sb = new StringBuffer();
			sb.append("{flag:true,msg:'审核人信息加载成功',")
			.append("auditor:'").append(auditor)
			.append("',hasAuth:").append(hasAuth)
			.append("}");	
			text = sb.toString();
		} catch (Exception e) {
			text = "{flag:false,msg:'参数异常，加载失败',auditor:'',hasAuth:false}";
			 log.error("审核人信息加载异常",e);
		}
	 
		return renderText(text);
	}
	
	/** adminId 为 null 即判断当前登录的管理员是否有审核权限*/
	private boolean hasAuth(String adminId,List<Admin> list){
		if(StringUtils.isBlank(adminId))
			adminId = getCurrentAdminId();
		if(DBInitId.CMS_SUPPER_ADMIN_ID.equals(adminId)) 
			return true;
		for(Admin a : list){
			if(a.getAdminId().equals(adminId)){
				return true;
			}
		}		
		return false;
	}
	
	/**
	 * 文章迁移
	 * @return
	 */
	@Action(value="category-movecontent")
	public String moveContent(){
		String text = "";
		Content cont = null;
		int num = 0;
		String[] idBatchs=getBatchIds();
		List<Content> contList = new ArrayList<Content>();
		try{
			for(int i=0;i<idBatchs.length;i++){
				contList = contentService.findByCatId(idBatchs[i]);
				if(contList.size()>0){
					for(int j=0;j<contList.size();j++){
						cont = contList.get(j);
						cont.setCategory(new Category(targetId));
						contentService.save2(cont);
						num ++;
					}
				}
			}
			if(num>0){
				text = "ok";
			}else{
				text = "zoro";
			}
		}catch(Exception e){
			LOG.error("文章移动异常", e);
		}
		return renderText(text);
	}
	
	
	public String getCatname() {
		return catname;
	}

	public void setCatname(String catname) {
		this.catname = catname;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getTargetId() {
		return targetId;
	}

	public void setTargetId(String targetId) {
		this.targetId = targetId;
	}

	public String getAuditType() {
		return auditType;
	}

	public void setAuditType(String auditType) {
		this.auditType = auditType;
	}

	public boolean isRefresh() {
		return refresh;
	}

	public void setRefresh(boolean refresh) {
		this.refresh = refresh;
	}
 
}